package web;

import mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.User;
import util.SqlSessionFactoryUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受注册传入的username password
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //封装对象
        User user1 = new User();
        user1.setUsername(username);
        user1.setPassword(password);

        //调用Mybatis完成查询
        //1 获取SqlSessionFactory对象
        /*String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSession();

        //2 获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3 获取mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4 调用方法
        User user = mapper.selectByUsername(username);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        //判断user是否为空
        if(user == null){
            //用户名可用
            mapper.insert(user1);
            //提交事务
            sqlSession.commit();
            writer.write("注册成功！");
            //释放资源
            sqlSession.close();

        }else{

            writer.write("用户名已存在！注册失败！");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
